# -*- coding: utf-8 -*-

import PIL
import PIL.Image as image
import os
import shutil
def resize(dir,eachpic):
    all = dir +os.sep+eachpic
    if os.path.getsize(all) / (1000 * 1000) >= 3 and all.endswith(".pdf"):
        img = image.open(all)
        # dpi = img.info["dpi"]
        size = img.size
        # img.resize((int(size[0] * 0.9), int(size[1] * 0.9)), image.ANTIALIAS)
        # img.save(all[:-4]+".pdf", "PDF",dpi=dpi)
        # resize(dir,eachpic)
        img.resize((int(size[0] * 0.9), int(size[1] * 0.9)), image.ANTIALIAS).save(all, "JPEG",quality=100)
        resize(dir,eachpic)
        # shutil.move(all, dir + os.sep + "translated\\" + eachpic)
        print("%s处理完毕"%eachpic)
    else:
        return 0

def to_pdf(dir,eachpic):

    all = dir +os.sep+eachpic
    print(all)
    if all.endswith(".jpg"):
        img = image.open(all)
        try:
            dpi = img.info["dpi"]
        except:
            dip = 96
        size = img.size
        img.save(all[:-4]+".pdf", "PDF",dpi=dpi)
        if os.path.getsize(all[:-4]+".pdf") / (1000*1000) >3:

            img.resize((int(size[0] * 0.9), int(size[1] * 0.9)), image.ANTIALIAS).save(all,"JPEG",quality=100,dpi = dpi)
            to_pdf(dir,eachpic)
        else:

            os.remove(all)
            print("%s转换完毕".decode("utf-8")%eachpic)
        # resize(dir,eachpic)
        # img.resize((int(size[0] * per), int(size[1] * per)), image.ANTIALIAS).save(all, "JPEG",quality=100)
        # shutil.move(all, dir + os.sep + "translated\\" + eachpic)
path = r"E:\意见单".decode("utf-8")

pic = os.listdir(path)
os.chdir(path)

for dir,a,file in os.walk(path):
    for eachpic in file:
        to_pdf(dir,eachpic)
# for dir, a, file in os.walk(path):
#     for eachpic in file:
#         resize(dir,eachpic)
        # print(dir,eachpic)
